// pages/index/index.js
const db = wx.cloud.database();
const app = getApp()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    isShowConfirm:false,
    date: new Date().getFullYear()+"-"+(new Date().getMonth()+1),
  },
  ChangeName(){
    if(!this.data.username){
    this.setData({
      isShowConfirm:true
    })}
  },
  setValue: function (e) {
    this.setData({
      username: e.detail.value
    })
  },
  cancel: function () {
    var that = this
    that.setData({
      isShowConfirm: false,
    })
  },
  confirmAcceptance:function(){
    var that = this
    console.log(this.data.username)
    that.setData({
      isShowConfirm: false,
    })
    db.collection("user").add({
      data:{name:this.data.username},
      success: function(res) {
        console.log("保存成功")
      },
      fail: function(res) {
        console.log("保存失败")
      }
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      username:app.globalData.username,
      all:app.globalData.all
    })
    console.log(app.globalData.all)
  },
  DateChange(e) {
    var that=this
    var [year,month]=e.detail.value.split("-")
    if(year>new Date().getFullYear()||(year==new Date().getFullYear()&&month>new Date().getMonth()+1))
      {this.setData({date: e.detail.value,all:[]}) 
      wx.showToast({
        title: '无打卡记录',
      })}
    else{
      const db = wx.cloud.database()
      db.collection('history').where({
        year:Number(year),
        month:Number(month)
      })
      .get({})
      .then(res=>{
        
        console.log("返回数据长度："+res.data.length)
        let newArr = []
        for (let i = 0; i < res.data.length; i++) {
          let leaveTimes=0
          let onTimes=0
          let username=res.data[i].username
          for (let j = 0; j < res.data[i].punchHistory.length; j++) {
            if(res.data[i].punchHistory[j].first=="请假"){leaveTimes++}
            else if(res.data[i].punchHistory[j].first=="准时"){onTimes++}
            if(res.data[i].punchHistory[j].second=="请假"){leaveTimes++}
            else if(res.data[i].punchHistory[j].second=="准时"){onTimes++}
          }
          newArr.push({ punchTimes:res.data[i].punchHistory.length,leaveTimes: leaveTimes, username: username ,onTimes:onTimes})
        }
          console.log(newArr)
        that.setData({
          date: e.detail.value,
          all:newArr
        })
      })
    }
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    
    
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})